package com.gotop.mapper.core.log.publisher;

import com.gotop.common.utils.ApplicationStringUtils;
import com.gotop.common.utils.WebUtil;
import com.gotop.entity.log.LogError;
import com.gotop.mapper.core.log.event.ErrorLogEvent;
import com.gotop.mapper.core.log.util.LogAbstractUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: cem
 * @description:
 * @author: superfish
 * @create: 2020-12-28 15:08
 **/
public class ErrorLogPublisher {
    public ErrorLogPublisher() {
    }

    public static void publishEvent(Throwable error, String requestUri) {
        HttpServletRequest request = WebUtil.getRequest();
        LogError logError = new LogError();
        logError.setRequestUri(requestUri);
        if (null != error) {
            logError.setStackTrace(getStackTraceAsString(error));
            logError.setExceptionName(error.getClass().getName());
            logError.setMessage(error.getMessage());
            StackTraceElement[] elements = error.getStackTrace();
            if (elements.length > 0) {
                StackTraceElement element = elements[0];
                logError.setMethodName(element.getMethodName());
                logError.setMethodClass(element.getClassName());
                logError.setFileName(element.getFileName());
                logError.setLineNumber(element.getLineNumber());
            }
        }

        LogAbstractUtil.addRequestInfoToLog(request, logError);
        Map<String, Object> event = new HashMap(16);
        event.put("log", logError);
        event.put("request", request);
        ApplicationStringUtils.publishEvent(new ErrorLogEvent(event));
    }

    // TODO输出
    public static String getStackTraceAsString(Throwable ex) {
        Writer stringWriter = new Writer() {
            @Override
            public void write(char[] cbuf, int off, int len) throws IOException {

            }

            @Override
            public void flush() throws IOException {

            }

            @Override
            public void close() throws IOException {

            }
        };
        ex.printStackTrace(new PrintWriter(stringWriter));
        return stringWriter.toString();
    }
}
